package cn.com.nes.site.service.patrolPlan.impl;

import cn.com.nes.common.em.EquipmentDamageLevelEnum;
import cn.com.nes.common.em.TimeType;
import cn.com.nes.common.util.TimeUtils;
import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.common.web.CommonResult;
import cn.com.nes.mybatis.agent.ope.mapper.XzqhMapper;
import cn.com.nes.mybatis.callcenter.entity.CcUser;
import cn.com.nes.mybatis.callcenter.mapper.*;
import cn.com.nes.site.entity.PatrolPlanXzqh;
import cn.com.nes.site.entity.dto.patrolPlan.*;
import cn.com.nes.site.entity.vo.patrolPlan.*;
import cn.com.nes.site.entity.vo.workOrder.QueryPatrolPlanEquipmentRecordVo;
import cn.com.nes.site.service.patrolPlan.PatrolService;
import cn.com.nes.site.service.system.user.CcUserService;
import cn.com.nes.site.service.workOrder.dto.QueryPatrolPlanEquipmentRecordDto;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Range;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.text.DateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Pattern;

@Service
public class PatrolServiceImpl implements PatrolService {
    private static final Pattern numberPattern = Pattern.compile("^\\d+$");
    @Resource
    private PatrolPlanMapper patrolPlanMapper;
    @Resource
    private PatrolPlanDataItemMapper patrolPlanDataItemMapper;

    @Resource
    private PatrolPlanEquipmentRecordMapper patrolPlanEquipmentRecordMapper;

    @Resource
    private XzqhMapper xzqhMapper;

    @Resource
    private CcUserService ccUserService;
    @Resource
    private PatrolPlanXzqhMapper patrolPlanXzqhMapper;
    @Resource
    private PatrolEquipmentRecordDataItemValueMapper patrolEquipmentRecordDataItemValueMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<CreatePatrolPlanVo> createPatrolPlan(CreatePatrolPlanVo createPatrolPlanVo) {
        if (ObjectUtil.isNull(createPatrolPlanVo.getTitle())) {
            return CommonResult.error("标题不能为空");
        }
        if (ObjectUtil.isNull(createPatrolPlanVo.getYear())) {
            return CommonResult.error("年份不能为空");
        }
        if (ObjectUtil.isNull(createPatrolPlanVo.getStartTime())) {
            return CommonResult.error("开始时间不能为空");
        }
        if (ObjectUtil.isNull(createPatrolPlanVo.getEndTime())) {
            return CommonResult.error("结束时间不能为空");
        }
        if (ObjectUtil.isNull(createPatrolPlanVo.getXzqhdm())) {
            return CommonResult.error("行政区划代码不能为空");
        }
        String patrolPlanId = UUID.randomUUID().toString().replaceAll("-", "");
        //封装数据
        PatrolPlanDTO patrolPlan = new PatrolPlanDTO();
        patrolPlan.setTitle(createPatrolPlanVo.getTitle());
        patrolPlan.setYear(createPatrolPlanVo.getYear());
        patrolPlan.setStartTime(TimeUtils.getDateByString(createPatrolPlanVo.getStartTime(), TimeType.yyyy_MM_dd));
        patrolPlan.setEndTime(TimeUtils.getDateByString(createPatrolPlanVo.getEndTime(), TimeType.yyyy_MM_dd));
        //如果巡检计划开始时间小于当前时间, 立即开始巡检
        if (patrolPlan.getStartTime().before(new Date())) {
            patrolPlan.setStatus(1);
        }
        CcUser ccUser = ccUserService.getCcUser(createPatrolPlanVo.getUserInfo().getCallCenterUserId());
        patrolPlan.setAccount(ccUser.getAccount());
        patrolPlan.setXzqhdm(createPatrolPlanVo.getXzqhdm());
        patrolPlan.setPatrolPlanId(patrolPlanId);
        patrolPlan.setCompanyId(createPatrolPlanVo.getOperateUserCallCenterCompanyId());
        Long gmtTime = System.currentTimeMillis();
        patrolPlan.setGmtCreate(gmtTime);
        patrolPlan.setGmtModified(gmtTime);
        if (patrolPlanMapper.insert(patrolPlan) < 1) {
            return CommonResult.error("保存巡检计划表失败");
        }
        this.insertDefaultRecords(createPatrolPlanVo.getUserInfo().getCallCenterCompanyId(),patrolPlan.getPatrolPlanId(),createPatrolPlanVo.getUserInfo().getCallCenterUserId());
        this.addDefaultDataItems(patrolPlanId);
        /*else {
            List<String> xzqhdmList =
                    Arrays.stream(createPatrolPlanVo.getXzqhdms()).filter(code -> code.length() < 13)
                            .collect(Collectors.toList());
            PatrolPlanXzqh patrolPlanXzqh = null;
            for (String s : xzqhdmList) {
                patrolPlanXzqh = new PatrolPlanXzqh();
                patrolPlanXzqh.setPatrolPlanId(patrolPlan.getPatrolPlanId());
                patrolPlanXzqh.setGmtCreate(patrolPlan.getGmtCreate());
                patrolPlanXzqh.setGmtModified(patrolPlan.getGmtModified());
                patrolPlanXzqh.setXzqhdm(s);
                //插入patrol_plan_xzqh表
                if (patrolPlanXzqhMapper.insert(patrolPlanXzqh) < 1) {
                    throw new BusinessException("保存行政区划失败");
                }
            }
            this.insertDefaultRecords(createPatrolPlanVo.getUserInfo().getCallCenterCompanyId(),patrolPlanXzqh.getPatrolPlanId(),createPatrolPlanVo.getUserInfo().getCallCenterUserId());
            this.addDefaultDataItems(patrolPlanId);
        }*/
        return CommonResult.ok("保存成功");
    }

    @Override
    public Integer insertDefaultRecords(String companyId, String patrolPlanId, Long userId) {
        return patrolPlanEquipmentRecordMapper.insertDefaultRecords(companyId,patrolPlanId,userId);
    }
    @Override
    public void addDefaultDataItems(String patrolPlanId) {
        patrolPlanEquipmentRecordMapper.addDefaultDataItems(patrolPlanId);
    }
    @Override
    @Transactional(readOnly = true)
    public Page<QueryPatrolPlanByQueryDto> queryPatrolPlanByQuery(QueryPatrolPlanByQueryVo vo) {
        //如果不填默认自动获取
        if(ObjectUtil.isEmpty(vo.getCompanyId())){
            vo.setCompanyId(Long.parseLong(vo.getOperateUserCallCenterCompanyId()));
        }
        Page<QueryPatrolPlanByQueryDto> pageList =new Page<>(vo.getPageid(), vo.getPagesize());
        vo.setTableName(vo.isQueryHistory() ? "patrol_plan_his" : "patrol_plan");
        List<PatrolPlanDTO> patrolPlans;
        patrolPlans = patrolPlanMapper.queryPatrolPlanByQuery(vo);
        List<QueryPatrolPlanByQueryDto> dtos = new ArrayList<>();
        DateFormat df = TimeUtils.dateFormat(TimeType.yyyy_MM_dd.value());
        DateFormat df1 = TimeUtils.dateFormat(TimeType.yyyy_MM_dd_HH_mm_ss.value());
        for (PatrolPlanDTO patrolPlan : patrolPlans) {
            QueryPatrolPlanByQueryDto dto = new QueryPatrolPlanByQueryDto();
            dto.setPatrolPlanId(patrolPlan.getPatrolPlanId());
            dto.setTitle(patrolPlan.getTitle());
            dto.setYear(patrolPlan.getYear());
            if (patrolPlan.getStartTime() != null) {
                dto.setStartTime(df.format(patrolPlan.getStartTime()));
            }
            if (patrolPlan.getEndTime() != null) {
                dto.setEndTime(df.format(patrolPlan.getEndTime()));
            }
            dto.setStatus(patrolPlan.getStatus());
            dto.setUser(patrolPlan.getAccount());
            dto.setId(patrolPlan.getId());
            if (patrolPlan.getGmtCreate() != null) {
                dto.setCreateTime(df1.format(new Date(patrolPlan.getGmtCreate())));
            }
            Map<String, Object> result = patrolPlanMapper.queryPatrolPlanCount(patrolPlan.getId(), vo.getTableName());
            if(result == null) {
                result = Collections.emptyMap();
            }
            Integer regions = toNumber(result.get("regions"));
            Integer patrolEquipmentCount = toNumber(result.get("patrolEquipmentCount"));
            Integer patrolEquipmentFailCount = toNumber(result.get("patrolEquipmentFailCount"));
            Integer patrolEquipmentSuccessCount = toNumber(result.get("patrolEquipmentSuccessCount"));
            Integer patrolEquipmentWillCount = toNumber(result.get("patrolEquipmentWillCount"));
            Integer patrolEquipmentFinishCount = toNumber(result.get("patrolEquipmentFinishCount"));
            dto.setRegions(regions);
            dto.setPatrolEquipmentCount(patrolEquipmentCount);
            dto.setPatrolEquipmentFailCount(patrolEquipmentFailCount);
            dto.setPatrolEquipmentSuccessCount(patrolEquipmentSuccessCount);
            dto.setPatrolEquipmentWillCount(patrolEquipmentWillCount);
            dto.setPatrolEquipmentFinishCount(patrolEquipmentFinishCount);
            dtos.add(dto);
        }
        pageList.setRecords(dtos);
        return pageList;
    }
    private Integer toNumber(Object o) {
        if(o != null) {
            String s = o.toString();
            if(numberPattern.matcher(s).find()) {
                return Integer.parseInt(s);
            }
        }
        return null;
    }


    @Override
    public Page<QueryPatrolPlanEquipmentRecordDto>queryPatrolPlanEquipmentRecordByQuery(QueryPatrolPlanEquipmentRecordVo vo) {

        //设置默认分页
        if (ObjectUtil.isNull(vo.getPage())) {
            vo.setPage(1);
        }
        if (ObjectUtil.isNull(vo.getSize())) {
            vo.setSize(10);
        }
        // 判断传入的年份
        if (StrUtil.isEmpty(vo.getYear())) {
            String year = String.valueOf(LocalDate.now().getYear());
            vo.setYear(year);
        }
        Page<QueryPatrolPlanEquipmentRecordDto> pageList =new Page<>(vo.getPageid(), vo.getPagesize());
        String userXzqh = vo.getUserInfo().getAreacode();
        if (org.apache.commons.lang3.StringUtils.isBlank(userXzqh)) {
            vo.setXzqhdm("86");
        }
        String xzqhdm =  handleXzqhdm(vo.getXzqhdm());
        vo.setXzqhdm(xzqhdm);
        if(StringUtils.isEmpty(vo.getYear())){
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            vo.setYear(String.valueOf(year));
        }

        vo.setPlanTableName("patrol_plan");
        vo.setRecordTableName("patrol_plan_equipment_record");
        List<QueryPatrolPlanEquipmentRecordDto> dtos = patrolPlanEquipmentRecordMapper.queryPatrolPlanEquipmentRecordByQuery(vo);
        if (dtos == null || dtos.size() == 0) {
            vo.setPlanTableName("patrol_plan_his");
            vo.setRecordTableName("patrol_plan_equipment_record_his");
            dtos = patrolPlanEquipmentRecordMapper.queryPatrolPlanEquipmentRecordByQuery(vo);
        }
        dtos = handlePatrlResult(dtos);
        for(int i = 0; i < dtos.size(); i++) {
            dtos.get(i).setNo(String.valueOf(i + 1));
        }
        dtos.forEach(dto -> dto.setDamageLevelName(Optional
                .ofNullable(EquipmentDamageLevelEnum.getEnumByLevel(dto.getDamageLevel()))
                .map(EquipmentDamageLevelEnum::getName).orElse("")));
        pageList.setRecords(dtos);
        return pageList;
    }

    /**
     * 处理计划查询结果
     * @param dtos
     * @return
     */
    public List<QueryPatrolPlanEquipmentRecordDto> handlePatrlResult(List<QueryPatrolPlanEquipmentRecordDto> dtos) {
        for (QueryPatrolPlanEquipmentRecordDto dto: dtos){
            PatrolServiceImpl patrolService = new PatrolServiceImpl();
            int status = 0;
            if (ObjectUtil.isNotNull(dto.getStatus())&& ObjectUtil.isNotNull(dto.getResult())){
                status =patrolService.handleStatus(dto.getStatus(),dto.getResult());
            }
            dto.setStatus(status);
            dto.setStatusName(status);
            if(ObjectUtil.isNull(dto.getPatrolPersonnel())){
                dto.setPatrolTime(null);
            }
            //判断该条巡检记录是否以超期
            Date endTime = dto.getEndTime();
            int compareTo = endTime.compareTo(new Date());
            if(compareTo == -1){
                dto.setIsOverTime(1);
            }else{
                dto.setIsOverTime(0);
            }
            //审核失败时, 查询得到的巡检时间和巡检人为空
            if (dto.getStatus() == 6 && StrUtil.isNotBlank(dto.getTaskId())) {
                //获取任务id
                String taskId = dto.getTaskId();
                HashMap<String, Object> nameAndTime;
                try {
                    /* nameAndTime = patrolPlanEquipmentRecordMapper.getPreRecord(taskId);*/
                } catch (Exception e) {
                    continue;
                }
               /* if (ObjectUtil.isNotNull(nameAndTime)) {
                    if (nameAndTime.containsKey("name")) {
                        dto.setPatrolPersonnel((String) nameAndTime.get("name"));
                    }
                    if (nameAndTime.containsKey("time")) {
                        dto.setPatrolTime((Date) nameAndTime.get("time"));
                    }
                }*/
            }
        }
        return dtos;
    }
    /**
     * 根据任务id获取当前任务状态码
     * @param status
     * @param result
     * @return
     */
    public  int handleStatus(int status ,int result) {
        //0 待检查 1待用户确认 2检查失败 3待审核 4 用户拒签 5巡检完成 6审核失败
        int res =0;
        //已巡检
        if (1 == status) {
            //巡检失败
            if (0 == result) {
                res = 2;
                //巡检成功  待用户确认
            } else if (1 == result) {
                res = 1;
            }
            //用户确认
        } else if (2 == status) {
            //用户拒签
            if (0 == result) {
                res = 4;
                //用户签字 待审核
            } else if (1 == result) {
                res = 3;
            }
            //管理员审核
        } else if (3 == status) {
            //审核失败
            if (0 == result) {
                res = 6;
                //审核成功 巡检完成
            } else if (1 == result) {
                res = 5;
            }
            //待巡检
        }
        return res;
    }
    /**
     * 处理行政区划代码
     * @param xzqhdm
     * @return
     */
    private String handleXzqhdm(String xzqhdm) {
        //处理型行政区划
        if (StrUtil.isNotBlank(xzqhdm)) {
            String level = xzqhMapper.getXzqhJb(xzqhdm);
            xzqhdm = xzqhdm.substring(0, Integer.valueOf(XzqhUtils.subXzqhDigit(level)));
        }
        return xzqhdm;
    }

    /**
     * 处理巡检任务
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HashMap<String, Object> handlePatrolPlanEquipmentRecord(HandlePatrolPlanEquipmentReccordVo vo, Integer userType) {
        Long lastRecordId =0L;
        Long recordId;
        String taskId = null;
        Long userId = null;
        //判断任务id是否为空
        if(StrUtil.isEmpty(vo.getTaskId())){
            //根据计划id 和设备id查询该巡检记录
            PatrolPlanEquipmentRecord record = patrolPlanEquipmentRecordMapper.getPatrolPlanRecordBySbIdAndPlanId(vo.getPatrolPlanId(), vo.getSbId());
            HashMap<String, Object> stringObjectHashMap = confirmTheStatus(record, vo);
            if ("1".equals(stringObjectHashMap.get("res"))){
                return stringObjectHashMap;
            }
            record.setGmtModified(null);
            record.setIsNew((byte)0);
            patrolPlanEquipmentRecordMapper.updateById(record);
            //如果为空则创建新巡检记录
            record.setId(null);
            record.setTaskId(UUID.randomUUID().toString().replaceAll("-", "").substring(0,30));
            record.setStatus((vo.getRecordStatus()).byteValue());
            record.setUserId(vo.getUserId());
            record.setTime(new Date());
            record.setResultDesc(vo.getDesc());
            if(vo.getStatus() ==0){
                record.setRecord("提交检查结果,检查失败");
            }else if(vo.getStatus() ==1){
                record.setRecord("提交检查结果,检查成功");
            }
            record.setResult((vo.getStatus().byteValue()));
            if (ObjectUtil.isNotNull(vo.getIsLive())){
                record.setIsLive(vo.getIsLive());
            }
            if (ObjectUtil.isNotNull(vo.getIsUse())){
                record.setIsUse(vo.getIsUse());
            }
            record.setIsNew((byte)1);
            //传入图片地址不为空, 添加图片地址
            if (StrUtil.isNotEmpty(vo.getImages())) {
                record.setImages(vo.getImages());
                //传图片必须同时上传经纬度

            }
            if (ObjectUtil.isNotNull(vo.getIsInsured())){
                record.setIsInsured(vo.getIsInsured());
            }
            if (StrUtil.isNotBlank(vo.getWarrantyExpiryDate())){
                record.setWarrantyExpiryDate(vo.getWarrantyExpiryDate());
            }
            record.setGmtCreate(System.currentTimeMillis());
            record.setLongitude(vo.getLongitude());
            record.setLatitude(vo.getLatitude());
            record.setDamageLevel(vo.getDamageLevel());
            patrolPlanEquipmentRecordMapper.insert(record);
            recordId = record.getId();
            taskId = record.getTaskId();
        }else{
            //不为空根据任务id查询最新巡检记录
            PatrolPlanEquipmentRecord lastRecord= patrolPlanEquipmentRecordMapper.selectNewRecordByTaskId(vo.getTaskId());
            HashMap<String, Object> stringObjectHashMap = confirmTheStatus(lastRecord, vo);
            if ("1".equals(stringObjectHashMap.get("res"))){
                return stringObjectHashMap;
            }
            if ("no".equals(vo.getIsBxj())){
                lastRecord = patrolPlanEquipmentRecordMapper.getPatrolPlanRecordBySbIdAndPlanId(vo.getPatrolPlanId(), vo.getSbId());
                lastRecord.setTaskId(vo.getTaskId());
            }
            //上一条记录为检查不通过
            if (vo.getRecordStatus() == 2 && lastRecord.getStatus().equals((byte)1) && lastRecord.getResult().equals((byte)0)) {
                lastRecord.setIsNew((byte) 1);
                if (StrUtil.isNotEmpty(vo.getSignImage())) {
                    lastRecord.setSignImage(vo.getSignImage());
                }
                patrolPlanEquipmentRecordMapper.updateById(lastRecord);
            }else {
                lastRecordId = lastRecord.getId();
                lastRecord.setIsNew((byte) 0);
                lastRecord.setGmtModified(new Date());
                PatrolPlanEquipmentRecord record = new PatrolPlanEquipmentRecord();
                BeanUtil.copyProperties(lastRecord, record);
                userId = lastRecord.getUserId();
                //修改上一条巡检记录
                patrolPlanEquipmentRecordMapper.updateById(record);
                //根据原运检记录创建新的巡检记录
                lastRecord.setId(null);
                lastRecord.setLastStatus(lastRecord.getStatus());
                lastRecord.setStatus(vo.getRecordStatus().byteValue());
                lastRecord.setUserId(vo.getUserId());
                lastRecord.setTime(new Date());
                lastRecord.setResultDesc(vo.getDesc());
                lastRecord.setResult((vo.getStatus().byteValue()));
                lastRecord.setLongitude(vo.getLongitude());
                lastRecord.setLatitude(vo.getLatitude());
                if (ObjectUtil.isNotNull(vo.getIsLive())) {
                    lastRecord.setIsLive(vo.getIsLive());
                }
                if (ObjectUtil.isNotNull(vo.getIsUse())) {
                    lastRecord.setIsUse(vo.getIsUse());
                }
                lastRecord.setIsNew((byte) 1);
                //传入图片地址不为空, 添加图片地址
                if (StrUtil.isNotEmpty(vo.getImages())) {
                    lastRecord.setImages(vo.getImages());
                }
                //传入图片地址不为空, 添加图片地址
                if (StrUtil.isNotEmpty(vo.getSignImage())) {
                    lastRecord.setSignImage(vo.getSignImage());
                }
                if (ObjectUtil.isNotNull(vo.getIsInsured())) {
                    lastRecord.setIsInsured(vo.getIsInsured());
                }
                if (StrUtil.isNotBlank(vo.getWarrantyExpiryDate())) {
                    lastRecord.setWarrantyExpiryDate(vo.getWarrantyExpiryDate());
                }
                if (Range.closed(1, 4).contains(vo.getDamageLevel())) {
                    lastRecord.setDamageLevel(vo.getDamageLevel());
                }
                lastRecord.setGmtCreate(System.currentTimeMillis());
                if (vo.getRecordStatus() == 1) {
                    if (vo.getStatus() == 0) {
                        lastRecord.setRecord("提交检查结果,检查失败");
                    } else if (vo.getStatus() == 1) {
                        lastRecord.setRecord("提交检查结果,检查成功");
                    }
                } else if (vo.getRecordStatus() == 2) {
                    if (vo.getStatus() == 0) {
                        lastRecord.setRecord("用户签名确认,用户拒签");
                    } else if (vo.getStatus() == 1) {
                        if (vo.getIsUse() != null && vo.getIsLive() != null) {
                            String str = "提交检查结果,";
                            if (vo.getIsLive() == 0) {
                                str += "房子未居住 ";
                            }
                            if (vo.getIsUse() == 0) {
                                str += "设备未使用 ";
                            }
                            if (Range.closed(1, 4).contains(vo.getDamageLevel())) {
                                str += Optional.ofNullable(EquipmentDamageLevelEnum.getEnumByLevel(vo.getDamageLevel()))
                                        .map(it -> it.getName() + " ")
                                        .orElse("");
                            }
                            if (vo.getIsLive() == 1 && vo.getIsUse() == 1) {
                                str = "用户签名确认,用户签字";
                            }
                            lastRecord.setRecord(str);
                        } else {
                            lastRecord.setRecord("用户签名确认,用户签字");
                        }
                    }
                } else if (vo.getRecordStatus() == 3) {
                    if (vo.getStatus() == 0) {
                        lastRecord.setRecord("审核,审核失败");
                    } else if (vo.getStatus() == 1) {
                        lastRecord.setRecord("审核,审核成功");
                    }
                }
                patrolPlanEquipmentRecordMapper.insert(lastRecord);
            }
            recordId = lastRecord.getId();
            taskId = lastRecord.getTaskId();
        }
       /* //修改设备质保日期（插入设备时未插入 ） 后面可能还加installation_date 安装日期
        companyEquipmentPermissionMapper.updateWarrantyExpiryDateBySbId(vo.getWarrantyExpiryDate(),vo.getSbId());
        equipmentInfoMapper.updateWarrantyExpiryDateBySbId(vo.getWarrantyExpiryDate(),vo.getSbId());
*/
        //判断检查数据项值是否为空
        if(ObjectUtil.isNull(vo.getDateItemValue())){
            //为空获取原巡检记录的检查内容创建该记录检查内容
            List<PatrolEquipmentRecordDataItemValue> infoByRecordId = patrolEquipmentRecordDataItemValueMapper.getInfoByRecordId(lastRecordId);
            for (PatrolEquipmentRecordDataItemValue itemValue: infoByRecordId) {
                itemValue.setId(null);
                itemValue.setPatrolEquipemntRecordId(recordId);
                itemValue.setGmtCreate(System.currentTimeMillis());
                itemValue.setGmtModified(System.currentTimeMillis());
                patrolEquipmentRecordDataItemValueMapper.insert(itemValue);
            }
        }else{
            //不为空根据新检查内容创建
            List<ItemValueDto> dateItemValue = vo.getDateItemValue();
            for (ItemValueDto dto: dateItemValue ) {
                PatrolEquipmentRecordDataItemValue itemValue = new PatrolEquipmentRecordDataItemValue();
                itemValue.setPatrolEquipemntRecordId(recordId);
                itemValue.setPatrolPlanDataItemId(dto.getId());
                itemValue.setValue(dto.getValue().byteValue());
                itemValue.setIsDelete((byte)0);
                itemValue.setGmtCreate(System.currentTimeMillis());
                itemValue.setGmtModified(System.currentTimeMillis());
                patrolEquipmentRecordDataItemValueMapper.insert(itemValue);
            }
        }
        HashMap<String, Object> res = new HashMap<>(2);
        res.put("recordId", recordId);
        res.put("taskId", taskId);
        if (userType==0){
            res.put("userId", userId);
        }else if (userType == 2){
            res.put("userId", vo.getUserId());
        }else{
            res.put("userId", userId);
        }

        return res;
    }
    /**
     * 确认状态
     * @return
     */
    private HashMap<String, Object> confirmTheStatus(PatrolPlanEquipmentRecord record,HandlePatrolPlanEquipmentReccordVo vo){
        HashMap<String, Object> res = new HashMap();
        res.put("res","0");
        if ("no".equals(vo.getIsBxj())){
            PatrolPlanEquipmentRecord record1 = patrolPlanEquipmentRecordMapper.getPatrolPlanRecordBySbIdAndPlanId(vo.getPatrolPlanId(), vo.getSbId());
            if (record1.getStatus() != 0){
                res.put("res", "1");
            }
        }else {
            if (ObjectUtil.isNotNull(record)) {
                //1.提交巡检2.用户确认3.巡检审核
                if (vo.getRecordStatus() == 1) {
                    if (record.getStatus() != 0)
                        res.put("res", "1");
                }
                if (vo.getRecordStatus() == 2) {
                    if (record.getStatus() != 1 || StrUtil.isNotBlank(record.getSignImage()))
                        res.put("res", "1");
                }
            } else {
                res.put("res", "1");
            }
        }
        //1：不通过；0：通过
        return res;
    }

    /**
     * 根据设备,计划获取其检查内容
     * @param vo
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public Page<QueryPatrolDataItemDto> queryPatrolDataItem(QueryPatrolDataItemVo vo) {
        Page<QueryPatrolDataItemDto> pageList =new Page<>(vo.getPageid(), vo.getPagesize());
        return pageList.setRecords(patrolPlanDataItemMapper.queryPatrolDataItem(vo.getSbId(), vo.getPatrolPlanId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long updatePatrolPlan(UpdatePatrolPlanVo updatePatrolPlanVo) {
        Long id = 0L;
        //根据前台传来的id参数，查询PatrolPlan
        PatrolPlanDTO patrolPlan=patrolPlanMapper.selectById(updatePatrolPlanVo.getId());
        if(null!=patrolPlan){
            //封装数据
            patrolPlan.setTitle(updatePatrolPlanVo.getTitle());
            patrolPlan.setYear(updatePatrolPlanVo.getYear());
            patrolPlan.setStartTime(TimeUtils.getDateByString(updatePatrolPlanVo.getStartTime(), TimeType.yyyy_MM_dd));
            patrolPlan.setEndTime(TimeUtils.getDateByString(updatePatrolPlanVo.getEndTime(), TimeType.yyyy_MM_dd));
            //如果巡检计划开始时间小于当前时间, 立即开始巡检
            if (patrolPlan.getStartTime().before(new Date())) {
                patrolPlan.setStatus(1);
            }
            Long gmtTime = System.currentTimeMillis();
            patrolPlan.setGmtModified(gmtTime);
            patrolPlanMapper.updateById(patrolPlan);
            //修改patrol_plan_xzqh表
            //先删除
            PatrolPlanXzqh patrolPlanXzqh = new PatrolPlanXzqh();
            patrolPlanXzqh.setIsDelete((byte) 1);
            QueryWrapper<PatrolPlanXzqh> checkWrapper = new QueryWrapper<>();
            checkWrapper.eq("patrolPlanId",patrolPlan.getPatrolPlanId());
            patrolPlanXzqhMapper.update(patrolPlanXzqh,checkWrapper);
            //增加
            PatrolPlanXzqh xzqh=null;
            for (int i = 0; i < updatePatrolPlanVo.getXzqhdms().length; i++) {
                xzqh = new PatrolPlanXzqh();
                xzqh.setPatrolPlanId(patrolPlan.getPatrolPlanId());
                xzqh.setGmtCreate(patrolPlan.getGmtCreate());
                xzqh.setGmtModified(patrolPlan.getGmtModified());
                xzqh.setXzqhdm(updatePatrolPlanVo.getXzqhdms()[i]);
                //插入patrol_plan_xzqh表
                if(patrolPlanXzqhMapper.insert(xzqh)<1){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return 1L;
                }
            }
            return 0L;
        }else{
            return 1L;
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delPatrolPlanEquipmentRecord(String patrolPlanId,String sbId){
        PatrolPlanEquipmentRecord record = new PatrolPlanEquipmentRecord();
        record.setIsDelete((byte) 1);
        QueryWrapper<PatrolPlanEquipmentRecord> checkWrapper = new QueryWrapper<>();
        checkWrapper.eq("patrolPlanId",patrolPlanId);
        checkWrapper.eq("sbId",sbId);
        int i = patrolPlanEquipmentRecordMapper.update(record, checkWrapper);
        return i;
    }
    /**
     * 关闭计划
     *
     * @param id 计划自增id
     * @return 关闭结果
     */
    @Override
    public Integer terminatePlan(Long id) {
        PatrolPlanDTO patrolPlan = new PatrolPlanDTO();
        patrolPlan.setId(id);
        //巡检计划状态置为3
        patrolPlan.setStatus(3);
        //修改计划结束时间
        patrolPlan.setEndTime(new Date(System.currentTimeMillis()));
        return patrolPlanMapper.updateById(patrolPlan);
    }
}
